<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="租户名搜索" style="width: 200px;" class="filter-item" clearable/>
      <el-input v-model="listQuery.appName" placeholder="app名称搜索" style="width: 200px;" class="filter-item" clearable/>
      <!-- 筛选tenant类型-->
      <el-select class="tenant-type-select" v-model="listQuery.type" filterable placeholder="请选择租户类型">
        <el-option
          v-for="item in tenantTypeList"
          :key="item.key"
          :label="item.value"
          :value="item.key">
        </el-option>
      </el-select>
      <!-- 所属租户组名称 搜索-->
      <el-input v-model="listQuery.groupName" placeholder="所属租户组名称搜索" style="width: 200px;" class="filter-item" clearable/>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建租户
      </el-button>
    </div>
    <el-table :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-popover
            placement="top-start"
            width="360"
            trigger="hover"
            content="禁用用户登录将禁止所有属于该租户的用户登录app">
            <el-button :type="row.forbidAllUserLogin | filterForbidAllUserLoginBtnType" size="mini" slot="reference"
                       @click="forbidAllUserLogin(row)">
              {{row.forbidAllUserLogin | filterForbidAllUserLogin}}
            </el-button>
          </el-popover>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="租户名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="描述">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="租户类型">
        <template slot-scope="scope">
          <span>{{ scope.row.type| filterTenantType }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="所属租户组">
        <template slot-scope="scope">
          <span>{{ scope.row.groupName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="关联app">
        <template slot-scope="scope">
          <span>{{ scope.row.appList| filterAppFullName }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNumber"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <CreateTenant
      ref="createTenantForm"
      :text-map="textMap"
      :dialog-status="dialogStatus"
      :dialog-form-visible.sync="dialogFormVisible"
      @on-fresh-list="getList"
    />

  </div>
</template>

<script>
  import * as apiTenant from '@/api/tenant'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import CreateTenant from '@/views/tenant/createTenant'
  import { MessageBox } from 'element-ui'

  export default {
    name: 'Tenant',
    components: { Pagination, CreateTenant },
    directives: { waves, permission },
    filters: {
      filterAppFullName(appList) {
        if (appList.length == 0) {
          return '无'
        }
        let appNameList = []
        appList.forEach((app) => {
          appNameList.push(app.fullname)
        })
        return appNameList.join(',')
      },
      filterForbidAllUserLoginBtnType(flag) {
        if (flag == false) {
          return 'danger'
        } else {
          return 'success'
        }
      },
      filterForbidAllUserLogin(flag) {
        if (flag == false) {
          return '禁用用户登录'
        } else {
          return '启用用户登录'
        }
      },
      filterTenantType(tenantType) {
        if (tenantType === 'common') {
          return '一般租户'
        } else if (tenantType === 'group') {
          return '租户组'
        }
      }
    },
    data() {
      return {
        list: null,
        total: 0,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 50,
          name: undefined,
          appName: undefined,
          type: undefined,
          groupName: undefined
        },
        tenantTypeList: [
          { key: undefined, value: 'ALL' },
          { key: 'common', value: '一般租户' },
          { key: 'group', value: '租户组' }
        ],
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        }
      }
    },
    created() {
      this.getList()
    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      // alert('离开用户管理界面')
    },
    methods: {
      async getList() { // 获取列表数据
        const { content } = await apiTenant.getList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },
      handleCreate() {
        this.$refs['createTenantForm'].clearFormData() // 直接调用子组件的method, 很方便
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['createTenantForm'].$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        console.log('row--->', row)
        const currentRow = Object.assign({}, row)
        this.$refs['createTenantForm'].setCurrentRow(currentRow)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['createTenantForm'].$refs['dataForm'].clearValidate()
        })
      },
      async forbidAllUserLogin(row) { //禁用or启用该tenant下所有app 用户的登录功能
        const tenantId = row.id
        let flag = ''
        const curStatus = row.forbidAllUserLogin
        if (curStatus == false) {
          flag = 'disable'
        } else {
          flag = 'enable'
        }
        await apiTenant.forbidAllUserLogin(tenantId, flag)
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        // 刷新列表数据
        this.getList()
      },
      handleDelete(row) {
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const deleteData = Object.assign({}, row) // copy obj
          apiTenant.deleteTenant(deleteData.id).then(() => {
            // 刷新列表数据
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        }).catch(() => {
        })
      }
    }
  }
</script>

<style scoped>
  .tenant-type-select {
    position: relative;
    top: -4px;
  }

</style>
